{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "view-in-github"
   },
   "source": [
    "<a href=\"https://colab.research.google.com/github/google/neural-tangents/blob/main/notebooks/weight_space_linearization.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "9uPYkWOcghJm",
    "pycharm": {}
   },
   "source": [
    "##### Copyright 2019 Google LLC.\n",
    "\n",
    "Licensed under the Apache License, Version 2.0 (the \"License\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "YDnknGorgv2O",
    "pycharm": {}
   },
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "https://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "2D2hQ1z3kmNu",
    "pycharm": {}
   },
   "source": [
    "#### Import & Utils"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "cxFbqXZKhGW0",
    "pycharm": {}
   },
   "source": [
    "Install JAX, Tensorflow Datasets, and Neural Tangents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "g_gSbMyUhF92",
    "pycharm": {}
   },
   "outputs": [],
   "source": [
    "!pip install -q --upgrade pip\n",
    "!pip install -q --upgrade jax[cuda11_cudnn82] -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html\n",
    "!pip install -q tensorflow-datasets\n",
    "!pip install -q git+https://www.github.com/google/neural-tangents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "8D0i89hRmNoC",
    "pycharm": {}
   },
   "outputs": [],
   "source": [
    "from jax import jit\n",
    "from jax import grad\n",
    "from jax import random\n",
    "\n",
    "import jax.numpy as jnp\n",
    "from jax.nn import log_softmax\n",
    "from jax.example_libraries import optimizers\n",
    "\n",
    "import tensorflow_datasets as tfds\n",
    "\n",
    "import neural_tangents as nt\n",
    "from neural_tangents import stax"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "-W1ws1B-6_vq",
    "pycharm": {}
   },
   "outputs": [],
   "source": [
    "def process_data(data_chunk):\n",
    "  \"\"\"Flatten the images and one-hot encode the labels.\"\"\"\n",
    "  image, label = data_chunk['image'], data_chunk['label']\n",
    "\n",
    "  samples = image.shape[0]\n",
    "  image = jnp.array(jnp.reshape(image, (samples, -1)), dtype=jnp.float32)\n",
    "  image = (image - jnp.mean(image)) / jnp.std(image)\n",
    "  label = jnp.eye(10)[label]\n",
    "\n",
    "  return {'image': image, 'label': label}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "32Wvhil9X8IK",
    "pycharm": {}
   },
   "source": [
    "# Weight Space Linearization"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Ajz_oTOw72v8",
    "pycharm": {}
   },
   "source": [
    "Setup some experiment parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "UtjfeaYC72Gs",
    "pycharm": {}
   },
   "outputs": [],
   "source": [
    "learning_rate = 1.0\n",
    "batch_size = 128\n",
    "training_epochs = 5\n",
    "steps_per_epoch = 50000 // batch_size"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "JJ_zDKsKcDB-",
    "pycharm": {}
   },
   "source": [
    "Create MNIST data pipeline using TensorFlow Datasets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "5llaSqZW4Et3",
    "pycharm": {}
   },
   "outputs": [],
   "source": [
    "train_data = tfds.load('mnist:3.*.*', split=tfds.Split.TRAIN)\n",
    "train_data = tfds.as_numpy(\n",
    "    train_data.shuffle(1024).batch(batch_size).repeat(training_epochs))\n",
    "test_data = tfds.load('mnist:3.*.*', split=tfds.Split.TEST)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "1-nKR--j5p2C",
    "pycharm": {}
   },
   "source": [
    "Create a Fully-Connected Network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "wIbfrdzq5pLZ",
    "pycharm": {}
   },
   "outputs": [],
   "source": [
    "init_fn, f, _ = stax.serial(\n",
    "    stax.Dense(512, 1., 0.05),\n",
    "    stax.Erf(),\n",
    "    stax.Dense(10, 1., 0.05))\n",
    "\n",
    "key = random.PRNGKey(0)\n",
    "_, params = init_fn(key, (-1, 784))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "c9zgKt9B8NBt",
    "pycharm": {}
   },
   "source": [
    "Linearize the network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "bU6ccJM_8LWt",
    "pycharm": {}
   },
   "outputs": [],
   "source": [
    "f_lin = nt.linearize(f, params)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Lrp9YNCt7nCj",
    "pycharm": {}
   },
   "source": [
    "Create an optimizer and initialize it for the full network and the linearized network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "J-8i_4KD7o5s",
    "pycharm": {}
   },
   "outputs": [],
   "source": [
    "opt_init, opt_apply, get_params = optimizers.momentum(learning_rate, 0.9)\n",
    "\n",
    "state = opt_init(params)\n",
    "lin_state = opt_init(params)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "NspVdDOU8mhk",
    "pycharm": {}
   },
   "source": [
    "Create a cross-entropy loss function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "z6L-LzyF8qLW",
    "pycharm": {}
   },
   "outputs": [],
   "source": [
    "loss = lambda fx, y_hat: -jnp.mean(log_softmax(fx) * y_hat)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "NHVIPtg79Gt4",
    "pycharm": {}
   },
   "source": [
    "Specialize the loss to compute gradients of the network and linearized network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "-Z5uKwva9NB9",
    "pycharm": {}
   },
   "outputs": [],
   "source": [
    "grad_loss = jit(grad(lambda params, x, y: loss(f(params, x), y)))\n",
    "grad_lin_loss = jit(grad(lambda params, x, y: loss(f_lin(params, x), y)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "rWROOyCZ9u6N",
    "pycharm": {}
   },
   "source": [
    "Train the network and its linearization."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "colab": {
     "height": 151
    },
    "colab_type": "code",
    "executionInfo": {
     "elapsed": 24126,
     "status": "ok",
     "timestamp": 1583914391854,
     "user": {
      "displayName": "",
      "photoUrl": "",
      "userId": ""
     },
     "user_tz": 420
    },
    "id": "WXeof-AB8BiV",
    "outputId": "41fed5fb-957c-4623-e7a2-486119501a23",
    "pycharm": {}
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch\tLoss\tLinear Loss\n",
      "0\t0.2529\t0.2529\n",
      "1\t0.0750\t0.0759\n",
      "2\t0.0498\t0.0513\n",
      "3\t0.0585\t0.0595\n",
      "4\t0.0514\t0.0530\n",
      "5\t0.0446\t0.0467\n",
      "6\t0.0408\t0.0423\n"
     ]
    }
   ],
   "source": [
    "print ('Epoch\\tLoss\\tLinear Loss')\n",
    "epoch = 0\n",
    "\n",
    "for i, batch in enumerate(train_data):\n",
    "  batch = process_data(batch)\n",
    "  X, Y = batch['image'], batch['label']\n",
    "\n",
    "  params = get_params(state)\n",
    "  state = opt_apply(i, grad_loss(params, X, Y), state)\n",
    "\n",
    "  lin_params = get_params(lin_state)\n",
    "  lin_state = opt_apply(i, grad_lin_loss(lin_params, X, Y), lin_state)\n",
    "\n",
    "  if i % steps_per_epoch == 0:\n",
    "    print('{}\\t{:.4f}\\t{:.4f}'.format(\n",
    "        epoch, loss(f(params, X), Y), loss(f_lin(lin_params, X), Y)))\n",
    "    epoch += 1\n"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [
    "2D2hQ1z3kmNu"
   ],
   "last_runtime": {
    "build_target": "//learning/deepmind/dm_python:dm_notebook3",
    "kind": "private"
   },
   "name": "Weight Space Linearization.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
